<template>
  <div class="calendar" ref="el">
    <CalendarHead />
    <div class="cell-wrap">
      <!-- transition内置动画标签，只能包含一个元素且只生效一个；元素标签需要设置v-show、v-if控制显示。
           name属性定义动画类名属性值-xxx ,appear一开始就生效动画-->
      <transition :name="transitionName" appear>
        <component :is="componentName" />
      </transition>
    </div>
    <Mask :position="position"></Mask>
  </div>
</template>

<script>
import { computed, onMounted, provide, ref, watch } from "vue";
import dayjs from "dayjs";
import useMousePosition from "@/hooks/useMousePosition";
import * as Children from "./children";

export default {
  name: "calendar",
  components: {
    ...Children,
  },
  setup() {
    const el = ref(null);
    let position = ref(null)
    const displayMode = ref("date");  // 时间格式
    const date = ref(dayjs().toDate());
    const transitionName = ref("out");  // 动画样式
    const componentName = ref("date-panel");
    const levels = ["date", "month", "year"];
    position.value = useMousePosition(el);
    
    // 监听展示的时间格式，并及时转化组件
    watch(displayMode, (now, old) => {
      const nowLevel = levels.indexOf(now);
      const oldLevel = levels.indexOf(old);
      // 当从大时间切换到小时间，使用out弹出，否则使用in进入
      transitionName.value = nowLevel < oldLevel ? "out" : "in";
      // componentName必须在transitionName设置之后或同时设置才不会使transitionName滞后
      componentName.value = {
        date: "date-panel",
        month: "month-panel",
        year: "year-panel",
      }[displayMode.value];
    });

    // 设置时间
    const setDate = (value) => {
      date.value = dayjs(value).toDate();
    };

    // 设置头部时间展示
    const setDisplayMode = (mode) => {
      displayMode.value = mode;
    };

    // 提供子组件值
    provide("displayMode", [displayMode, setDisplayMode]);
    provide("date", [date, setDate]);

    return {
      el,
      position,
      componentName,
      transitionName,
    };

  },
  onMounted() {
    el.value.addEventListener('mousemove', () => {
      position.value = useMousePosition(el)
    })
  }
};
</script>

<style lang="less" rel="stylesheet/less">
// 动画
@import "./transition";

.calendar {
  position: relative;
  user-select: none;
  overflow: hidden;
  width: 350px;
  padding: 10px;
  background-color: #000;
  color: #fff;

  .cell-wrap {
    overflow: hidden;
    height: 310px;
    position: relative;
  }

  .cell-list {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    text-align: center;

    .cell-item {
      &:hover {
        position: relative;
        z-index: 1;
      }

      span {
        z-index: 1;
        position: relative;
      }
    }
  }

  .mask {
    width: 200%;
    height: 200%;
    pointer-events: none;
    position: absolute;
    top: 0;
    left: 0;
  }
}
</style>
